package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Map> findAll() {
        List<Menu> list = menuDao.findAll();
        List<Map> maps = new ArrayList<>();
        for (Menu menu : list) {
            Integer id = menu.getId();
            List<Menu> menuList = menuDao.findByParentId(id);
            menu.setChildren(menuList);
            if (menu.getChildren().size() > 0) {
                Map<String,Object> map = new HashMap<>();
                map.put("id",menu.getId());
                map.put("name",menu.getName());
                map.put("menus",menu.getChildren());
                maps.add(map);
            }
        }
        return maps;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Menu> page = menuDao.findByQueryString(queryString);
        long total = page.getTotal();
        List<Menu> rows = page.getResult();
        return new PageResult(total, rows);
    }
}
